#include "utils.h"
#include <stdlib.h>


utils::utils(void)
{
}


utils::~utils(void)
{
}

int8** utils::stringMapToArray( const std::string& str,uint32& width,uint32& height )
{
	/*{
		{1,0,0,0,0,0},
		{0,1,0,0,0,0},
		{0,0,1,0,0,0},
		{0,0,0,1,0,0},
	}*/
	string::size_type n=0,l=0,r=0; //,len=str.size();
	n = str.find_first_of('{',0)+1;	
	vector<string> vs;
	vs.clear();
	while(1)
	{
		l = str.find_first_of("{",n);
		r = str.find_first_of("}",n);
		if (l==string::npos||r==string::npos)
			break;
		string s = str.substr(l+1,r-l-1);
		vs.push_back(s);
		n = r+1;
	}

	height = vs.size();
	width = 0;
	int8 **map=NULL;
	vector<string> col;

	//height = 1000;

	for (size_t i=0;i<height;++i)
	{
		col.clear();
		split(vs[i],col,",");
		if (col.size()>0 )
		{
			if (width==0)
			{
				width=/*1000*/col.size();
				map = new int8*[height];
				for (uint32 j=0;j<height;++j)
				{
					map[j] = new int8[width];
				}
			}			
			for (size_t k=0;k<width;++k)
			{
				map[i][k] = /*(i*k+3)*i*k*3%2*/atoi(col[k].c_str());
			}
		}
	}

	return map;

}

void utils::split( const std::string & str, std::vector< std::string > & result, const std::string & sep )
{
	result.clear();
	

	if ( sep.size() == 0 )
	{
		split_withspace( str, result );
		return;
	}

	std::string::size_type i,j, len = str.size(), n = sep.size();

	i = j = 0;

	while ( i+n <= len )
	{
		if ( str[i] == sep[0] && str.substr( i, n ) == sep )
		{
			result.push_back( str.substr( j, i - j ) );
			i = j = i + n;
		}
		else
		{
			i++;
		}
	}
	result.push_back( str.substr( j, len-j ) );
}

void utils::split_withspace( const std::string & str, std::vector< std::string > & result )
{
	std::string::size_type i, j, len = str.size();
	for (i = j = 0; i < len; )
	{
		while ( i < len && ::isspace( str[i] ) ) i++;
		j = i;
		while ( i < len && ! ::isspace( str[i]) ) i++;


		if (j < i)
		{
			result.push_back( str.substr( j, i - j ));
			while ( i < len && ::isspace( str[i])) i++;
			j = i;
		}
	}
	if (j < len)
	{
		result.push_back( str.substr( j, len - j ));
	}
}